/**
 * Created by wangmeng on 2018/7/20.
 */
var param = new Object();
var map = {};//存储单元格信息(map形式，key是分区、value是该分区所有的单元格信息)
var url = path + "/common/exportExcel/listByPage";
$(function () {
    var fsqlgrid = $("#fsqltt");
    initFSqlGrid(fsqlgrid);
    fsqlgrid.datagrid({
        fit:false
    });
    fsqlgrid.datagrid("resize",{
        height:200
    });
    fsqlgrid.datagrid({
        //选中事件
        onClickRow: function (index, row) {
            // setCellData();
            $("#celltt").datagrid("loadData", {rows: []});
            var zoneNo = row.zoneNo;
            var rows = map[zoneNo];
            if(rows.length>0){
                $("#celltt").datagrid("loadData", {rows: rows});
            }
        },
        //双击事件
        onDblClickRow: function (index, row) {
            btnEditFSql();
        }
    });
    var cellgrid = $("#celltt");
    initCellGrid(cellgrid);
    cellgrid.datagrid({
        fit:false
    });
    cellgrid.datagrid("resize",{
        height:240
    });
});

//初始化分区定义表格和数据
function initFSqlGrid(grid) {
    var columns = [
        {
            field: "fSqlId", title: "ID", hidden: true,
            align: "left", sortable: false, resizable: true, width: 120
        },
        {
            field: "excelId", title: "ID", hidden: true,
            align: "left", sortable: false, resizable: true, width: 120
        },
        {
            field: "zoneNo",
            title: "分区序号",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 80
        },
        {
            field: "fetchType",
            title: "取数模式",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 100,
            formatter: function (value, row, index) {
                var fetchTypeText = "";
                if(value == 1) {
                    fetchTypeText = "固定取数";
                }else if(value == 2) {
                    fetchTypeText = "固定行取数";
                }else if(value == 3) {
                    fetchTypeText = "新增行取数";
                }
                return fetchTypeText;
            }
        },
        {
            field: "fetchSql",
            title: "取数SQL",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 500
        },
        {
            field: "dataType",
            title: "数据类型",
            align: "center",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 100,
            formatter: function (value, row, index) {
                var dataType = "";
                if(value == 1) {
                    dataType = "标题";
                }else if(value == 2) {
                    dataType = "抬头";
                }else if(value == 3) {
                    dataType = "表头";
                }else {
                    dataType = "数据";
                }
                return dataType;
            }
        },
        {
            field: "remark",
            title: "备注 ",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 300
        }
    ];
    //初始化datagrid无分页
    initDataGridWithoutPager(grid, columns, "#fsqltb");
    grid.datagrid({
        title:'分区信息'
    })
}
var cellTypeOption = [{ "value": 1, "text": "字符串" }, { "value": 2, "text": "金额" }];
//初始化单元格定义表格和数据
function initCellGrid(grid) {
    var columns = [
        {
            field: "cellId", title: "ID", hidden: true,
            align: "left", sortable: false, resizable: true, width: 120
        },
        {
            field: "fSqlId", title: "ID", hidden: true,
            align: "left", sortable: false, resizable: true, width: 120
        },
        {
            field: "zoneNo",
            title: "分区序号",
            align: "left",
            halign: "center",
            sortable: false,
            resizable: true,
            width: 80
        },
        {
            field: "orderNo",
            title: "顺序编号",
            align: "left",
            halign: "center",
            editor:{ type: 'numberbox', options: {min:1,required:true} },
            sortable: false,
            resizable: true,
            width: 80
        },
        {
            field: "fetchField",
            title: "取数字段",
            align: "left",
            halign: "center",
            editor:{ type: 'textbox', options: {required:true} },
            sortable: false,
            resizable: true,
            width: 200
        },
        {
            field: "startRow",
            title: "起始行号",
            align: "left",
            halign: "center",
            editor:{ type: 'numberbox', options: {min:0,required:true}},
            sortable: false,
            resizable: true,
            width: 80
        },
        {
            field: "mergeRow",
            title: "合并行数",
            align: "left",
            halign: "center",
            editor:{ type: 'numberbox', options: {min:1,required:true} },
            sortable: false,
            resizable: true,
            width: 80
        },
        {
            field: "startCol",
            title: "起始列号",
            align: "left",
            halign: "center",
            editor:{ type: 'numberbox', options: {min:0,required:true} },
            sortable: false,
            resizable: true,
            width: 80
        },
        {
            field: "mergeCol",
            title: "合并列数 ",
            align: "left",
            halign: "center",
            editor:{ type: 'numberbox', options: {min:1,required:true} },
            sortable: false,
            resizable: true,
            width: 80
        },
        {
            field: "cellType",
            title: "数据格式 ",
            align: "left",
            halign: "center",
            editor:{ type: 'combobox', options: {
                    data: cellTypeOption,
                    valueField: "value",
                    textField: "text",
                    editable: false,
                    required: true,
                    panelHeight: "auto"
                } },
            sortable: false,
            resizable: true,
            width: 150,
            formatter: function (value, row, index) {
                var cellType = "";
                if(value == 1) {
                    cellType = "字符串";
                }else if(value == 2) {
                    cellType = "金额";
                }
                return cellType;
            }
        }
    ];
    initGridWithCheckBoxCanEdit(grid, param, url, columns, "#celltb", "id");
    var options = $("#celltt").datagrid("options");
    options.onLoadSuccess = function (data) {
        $('#celltt').datagrid("fixRownumber");
    };
    grid.datagrid({
        title:'单元格信息'
    })
}

/**
 * 初始化 DataGrid控件信息带checkbox多选不分页 (默认选中)
 *
 * @param grid
 */
function initGridWithCheckBoxCanEdit(grid, params, url, columns, toolbar, fieldId) {
    // 初始化 DataGrid控件信息
    grid.datagrid({
        url : "",
        title : "",
        toolbar : toolbar,
        onClickCell: onClickCell,
        onAfterEdit: onAfterEdit,
        fit:false,
        loadMsg : "",
        queryParams : {},
        nowrap : true,
        striped : true,
        idField : fieldId,
        remoteSort : false,
        frozenColumns : [ [ {
            field : 'check',
            checkbox : true
        } ] ],
        columns : [ columns ],
        onLoadSuccess : function(data) {
            grid.datagrid('clearSelections');
        },
        onLoadError : function() {
            $("#loading").hide();
        }
    });
}

//新增分区信息
function btnAddFSql() {
    top.layer.open({
        type: 2,
        title: '新增分区',
        shadeClose: false,
        shade: 0.3,
        area: ['650px', '400px'],
        content: path+'/common/exportExcel/toAddFSql', //iframe的url
        maxmin: false,
        end: function callback() {
            var fSqlRows = getGlobalVariable("fSqlRow");
            var fSqlRow = JSON.parse(fSqlRows)[0];
            $("#fsqltt").datagrid('appendRow', fSqlRow);
        }
    });
}

//修改分区信息
function btnEditFSql() {
    var selectedItem = $('#fsqltt').datagrid('getSelected');
    if(!selectedItem){
        $.messager.alert("提示", "请选择需要修改的记录！", "info");
        return false;
    }
    var index = $("#fsqltt").datagrid('getRowIndex', selectedItem);
    var fSqlRows = [];    //设置完成的分区信息，用于界面间的传值
    fSqlRows.push(selectedItem);
    setGlobalVariable("fSqlRow",JSON.stringify(fSqlRows));
    top.layer.open({
        type: 2,
        title: '修改分区',
        sshadeClose: false,
        shade: 0.3,
        area: ['650px', '400px'],
        content: path+'/common/exportExcel/toAddFSql', //iframe的url
        maxmin: false,
        end: function callback() {
            var fSqlRows = getGlobalVariable("fSqlRow");
            var fSqlRow = JSON.parse(fSqlRows)[0];
            $('#fsqltt').datagrid('updateRow', {index: index, row: fSqlRow});
        }
    });
}

//删除分区信息
function  btnDelFSql() {
    var selectedItem = $('#fsqltt').datagrid('getSelected');
    if(!selectedItem){
        $.messager.alert("提示", "请选择需要删除的记录！", "info");
        return false;
    }
    $.messager.confirm("操作提示", "是否要删除选中的分区?", function (OK) {
        if(OK){
            var index = $("#fsqltt").datagrid('getRowIndex', selectedItem);
            $('#fsqltt').datagrid('deleteRow', index);
            //级联删除单元格信息
            $("#celltt").datagrid("loadData", {rows: []});
            var zoneNo = selectedItem.zoneNo;
            delete map[zoneNo];
        }
    });
}

//新增单元格信息
function btnAddCell() {
    var selectedItem = $('#fsqltt').datagrid('getSelected');
    if(!selectedItem){
        $.messager.alert("提示", "请先选择一个分区！", "info");
        return false;
    }
    var zoneNo = selectedItem.zoneNo;
    var fetchType = selectedItem.fetchType;
    if(fetchType == 1){//固定取数
        var newRow = new Object();
        newRow.zoneNo = zoneNo;
        newRow.orderNo = 1;
        newRow.fetchField = "";
        newRow.startRow = 0;
        newRow.mergeRow = 1;
        newRow.startCol = 0;
        newRow.mergeCol = 1;
        newRow.cellType = 1;
        $("#celltt").datagrid('appendRow', newRow);
        //存储数据到map
        var rows = $('#celltt').datagrid('getRows');
        map[zoneNo] = rows;
    }else{//2.固定行取数，3.新增行取数
        top.layer.open({
            type: 2,
            title: '新增单元格',
            shadeClose: false,
            shade: 0.3,
            area: ['510px', '550px'],
            content: path+'/common/exportExcel/toAddCell', //iframe的url
            maxmin: false,
            end: function callback() {
                var columnNames = getGlobalVariable("columnNames").split(",");
                for(var i=0;i<columnNames.length;i++){
                    var newRow = new Object();
                    newRow.zoneNo = zoneNo;
                    newRow.orderNo = 1;
                    newRow.fetchField = columnNames[i];
                    newRow.startRow = 0;
                    newRow.mergeRow = 1;
                    newRow.startCol = 0;
                    newRow.mergeCol = 1;
                    newRow.cellType = 1;
                    $("#celltt").datagrid('appendRow', newRow);
                }
                //存储数据到map
                var rows = $('#celltt').datagrid('getRows');
                map[zoneNo] = rows;
            }
        });
    }
}

//删除单元格信息
function  btnDelCell() {
    var rows = $('#celltt').datagrid('getSelections');
    if (rows.length == 0) {
        $.messager.alert("操作提示", "请选一条记录！", "info");
        return false;
    }else{
        $.messager.confirm("操作提示", "是否要删除选中的单元格信息?", function (OK) {
            if(OK){
                var deletedData = $('#celltt').datagrid('getChecked');
                var deletedDataLength = deletedData.length;
                var zoneNo = deletedData[0].zoneNo;
                for(var i=0;i<deletedDataLength;i++){
                    var rowIndex = $('#celltt').datagrid('getRowIndex', deletedData[0]);
                    $('#celltt').datagrid('deleteRow', rowIndex);
                }
                //存储数据到map
                var rows = $('#celltt').datagrid('getRows');
                map[zoneNo] = rows;
            }
        });
    }
}

$.extend($.fn.datagrid.methods, {
    editCell: function(jq,param){
        return jq.each(function(){
            var opts = $('#celltt').datagrid('options');
            var fields = $('#celltt').datagrid('getColumnFields',true).concat($('#celltt').datagrid('getColumnFields'));
            for(var i=0; i<fields.length; i++){
                var col = $('#celltt').datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] != param.field){
                    col.editor = null;
                }
            }
            $('#celltt').datagrid('beginEdit', param.index);
            for(var i=0; i<fields.length; i++){
                var col = $('#celltt').datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }
        });
    }
});

var editIndex = undefined;
function endEditing(){
    if (editIndex == undefined){return true}
    if ($('#celltt').datagrid('validateRow', editIndex)){
        $('#celltt').datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}
function onClickCell(index, field){
    if (endEditing()){
        $('#celltt').datagrid('selectRow', index)
            .datagrid('editCell', {index:index,field:field});
        editIndex = index;
    }
}
//单元格失去焦点执行的方法
function onAfterEdit(index, row, changes) {
    //存储数据到map
    var zoneNo = row.zoneNo;
    var rows = $('#celltt').datagrid('getRows');
    map[zoneNo] = rows;
}

//保存增加的数据
function submit_Add() {
    if (!validform("user_form")) {
        return false;
    }
    var sheetNo = $.trim($("#sheetNo").val());
    if(isNaN(sheetNo)){
        $.messager.alert("提示", "sheet索引必须是零或正整数！", "info");
        return false;
    }
    var finalParams = new Object();
    finalParams.type = "add";
    finalParams.excelCode =  $.trim($("#excelCode").val());
    finalParams.excelName =  $.trim($("#excelName").val());
    finalParams.sheetNo =  sheetNo;
    finalParams.sheetName =  $.trim($("#sheetName").val());
    var fSqlRows = $('#fsqltt').datagrid('getRows');
    var fSqlRowsData = JSON.stringify(fSqlRows);
    finalParams.fSqlList = fSqlRowsData;
    var cellRowData = JSON.stringify(map);
    finalParams.cellMap = cellRowData;
    $.ajax({
        type: "POST",
        url: path+'/common/exportExcel/save',
        data: finalParams,
        dataType: "json",
        success: function callback(data) {
            var analyMsg = data;
            if (analyMsg.code != '0000') {
                $.messager.alert('操作提示', analyMsg.msg, 'warning', function () {
                });
            } else {
                $.messager.alert("操作提示", "添加导出定义成功.", "info", function () {
                    // parent.btnQuery();
                    closeLayer();
                });
            }
        },
        error: function (data, textstatus) {
            $.messager.alert('操作提示', data.responseText, 'error', function () {
            });
        }
    });
}